#include"list.h"
ListNode* BuyNode(typedata x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		return NULL;
	}
	newnode->data = x;
	newnode->prev = newnode->next = NULL;
	return newnode;
}

bool ListNodeEmpty(ListNode* pphead)
{
	assert(pphead);
	return pphead->next == pphead;
}
ListNode* ListNodeCreate()
{
	ListNode* pphead = BuyNode(-1);
	pphead->prev = pphead->next = pphead;
	return pphead;
}
void Destroy(ListNode* pphead)
{
	assert(pphead);
	ListNode* cur = pphead->prev;
	while (cur->next != pphead)
	{
		ListNode* last = cur->prev;
		free(cur);
		cur = last;

	}
	free(pphead);
}
void Print(ListNode* pphead)
{
	ListNode* cur = pphead->next;
	while (cur != pphead)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("\n");

}
void FrontPush(ListNode* pphead, typedata x)
{
	assert(pphead);
	ListNode* newnode = BuyNode(x);
	ListNode* first = pphead->next;
	newnode->next = first;
	first->prev = newnode;
	pphead->next = newnode;
	newnode->prev = pphead;

}
void BackPush(ListNode* pphead, typedata x)
{
	assert(pphead);
	ListNode* newnode = BuyNode(x);
	ListNode* tail = pphead->prev;
	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = pphead;
	pphead->prev = newnode;
}


void FrontPop(ListNode* pphead)
{
	assert(pphead);
	assert(!ListNodeEmpty(pphead));
	ListNode* tail = pphead->next;
	ListNode* next = tail->next;
	next->prev = pphead;
	pphead->next = next;
	free(tail);
	
}
void BackPop(ListNode* pphead)
{
	assert(pphead);
	ListNode* tail = pphead->prev;
	ListNode* last = tail->prev;
	last->next = pphead;
	pphead->prev = last;
	free(tail);
}

ListNode* NodeFind(ListNode* pphead, typedata x)
{
	assert(pphead);
	ListNode* cur = pphead->next;
	while (cur != pphead)
	{
		if (cur->data == x)
		{
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
}
void NodeInert(ListNode* pphead, ListNode* pos, typedata x)
{
	assert(pphead);
	assert(!ListNodeEmpty(pphead));
	assert(pos);
	ListNode* last = pos->prev;
	ListNode* newnode = BuyNode(x);
	last->next = newnode;
	newnode->prev = last;
	newnode->next = pos;
	pos->prev = newnode;

}
void NodeInertAfter(ListNode* pos, typedata x)
{
	assert(pos);
	ListNode* newnode = BuyNode(x);
	ListNode* next = pos->next;
	pos->next = newnode;
	newnode->prev = pos;
	newnode->next = next;
	next->prev = newnode;

}